<template>
  <div class="uploadImage">
    <el-upload
      ref="upload"
      class="avatar-uploader"
      drag
      action
      :auto-upload="false"
      :file-list="uploadList"
      multiple
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-success="successUpload"
      :on-change="uploadFile"
    >
      <slot>

      </slot>
    </el-upload>
  </div>
</template>

<script>
import { uploadgetOssSts } from '@/api/common'
import { getFileNameUUID } from '@/utils/index'
import OSS from 'ali-oss'
export default {
  // againUpload 重新上传
  props: ['againUpload', 'tableList'],
  data() {
    return {
      fileList: [],
      uploadId: '',
      uploadList: [],
      folderName: '',
      file_name: ''
    }
  },
  mounted() {

  },
  methods: {

    async uploadFile(files, fileList) {
      console.log(files, this.tableList)
      const index = this.tableList.findIndex(item => item.name === files.name)
      const indexs = this.tableList.findIndex(item => item.chapter_title === files.name)
      if (index !== -1 && indexs !== -1) {
        this.$message.warning(`${files.name}已存在`)
        return false
      } else {
        this.fileList.push(files)
        const that = this
        const file = files.raw
        const res = await uploadgetOssSts({ bucket: 'zhangyu-priv' })// 向后端发请求获取信息
        this.multipartUpload(that, file, res)
        console.log(this.fileList, 'fileList')
      }
    },
    // 上传视频
    async multipartUpload(that, file, res) {
      const client = new OSS({
        bucket: 'zhangyu-priv',
        region: 'oss-cn-hangzhou',
        accessKeyId: res.data.data.access_key_id,
        accessKeySecret: res.data.data.access_key_secret,
        stsToken: res.data.data.security_token,
        refreshSTSToken: async () => {
          const token = await uploadgetOssSts({ bucket: 'zhangyu-priv' })// 向后端发请求获取信息
          console.log(token, 'token')
          return {
            accessKeyId: token.data.data.access_key_id,
            accessKeySecret: token.data.data.access_key_secret,
            stsToken: token.data.data.security_token
          }
        },
        refreshSTSTokenInterval: 300000
      })
      let fileName = getFileNameUUID()
      // let obj = file.name
      that.folderName = res.data.data.dir
      // var index = obj.lastIndexOf('.')
      // obj = obj.substring(index, obj.length)
      // console.log(obj, 'obj')
      // 生成的文件名，保留文件后缀名，进行拼接
      // fileName = getFileNameUUID() + file.file.name;;
      fileName = getFileNameUUID() + file.name
      console.log(fileName, 'fileName', that.folderName)
      try {
        // object-key可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
        const result = await client.multipartUpload(that.folderName + `${fileName}`, file, {
          progress: function (p, checkpoint) {
            // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
            //   tempCheckpoint = checkpoint
            const index = that.fileList.findIndex(item => item.uid === checkpoint.file.uid)
            console.log(Math.floor(p * 100))
            that.$set(that.fileList[index], 'progress', Math.floor(p * 100))
            that.$set(that.fileList[index], 'ossName', checkpoint.name)
            that.$emit('progress', that.fileList)
          }
        })
          .then((result) => {
            // 上传成功返回值，可针对项目需求写其他逻辑
            console.log(result, 'result', that.fileList)
            that.$message.success('上传成功')
            const url = result.res.requestUrls[0].split('?')[0]
            console.log(url, 'url')
            const index = that.fileList.findIndex(item => item.ossName === result.name)
            that.$set(that.fileList[index], 'down_url', url)
            that.$emit('resultUpload', that.fileList[index])
            this.fileList.splice(index, 1)
          })
      } catch (e) {
        console.log(e)
      }
    },
    // 上传成功
    successUpload(res, file) {
      console.log(res, file, 'success')
    },
    handleExceed(files, fileList) {
      console.log(files, fileList, 'handleExceed')
    },
    beforeUpload(file) {
      console.log(file, 'beforeUpload')
    }
  }
}
</script>
<style lang="scss" scoped>
.uploadImage {

    ::v-deep .el-upload-dragger{
        border: none;
        width: auto;
        height: auto;
        overflow: visible;
    }
    ::v-deep .el-upload-list{
        display: none;
    }
//   ::v-deep .avatar-uploader .el-upload {
//     border: 1px dashed #d9d9d9;
//     border-radius: 6px;
//     cursor: pointer;
//     position: relative;
//     overflow: hidden;
//   }
//   ::v-deep .avatar-uploader .el-upload:hover {
//     border-color: #409eff;
//   }
//   ::v-deep .avatar-uploader-icon {
//     font-size: 28px;
//     color: #8c939d;
//     width: 100px;
//     height: 100px;
//     line-height: 100px;
//     text-align: center;
//   }
//   ::v-deep .avatar {
//     width: 100px;
//     height: 100px;
//     display: block;
// //   }
//   ::v-deep .el-upload__tip {
//     font-size: 12px;
//     font-family: PingFangSC-Regular, PingFang SC;
//     font-weight: 400;
//     color: #999999;
//     line-height: 20px;
//     width: 350px;
//   }
}
</style>